package com.dada.tiku.web.controller;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.dada.tiku.pojo.TUser;
import com.dada.tiku.service.UserService;
import com.dada.tiku.utils.WxLoginUtils;
import com.dada.tiku.utils.WxResult;
import com.dada.tiku.web.filter.QyWxUtils;

@RestController

public class UserController {
	
	/*
	 * 检查用户是不是第一次登陆,有没有在数据库中创建对象,没有的话就创建
	 */
	@Reference
	private UserService userService; 
	
	@RequestMapping("/user/check")
	
	public String checkUser(@RequestBody TUser userInfo){
		if(userInfo ==null && userInfo.getOpenid() ==null){
			return JSON.toJSONString(WxResult.build(500, "用户信息不能为空"));
		}
		TUser user = userService.findUserByopenid(userInfo.getOpenid());
		if(user == null){
			//代表用户第一次登陆,没有在数据库中有对应的数据,创建用户
			WxResult result = userService.createUser(userInfo);
			return JSON.toJSONString(result);
		}
		return JSON.toJSONString(WxResult.ok());
	}
	
	@RequestMapping("/user/login")
	public Object login(String code) throws Exception{
		return QyWxUtils.getDataFromWx(WxLoginUtils.getUserInfo(code));
	}
	
	@RequestMapping("/user/userInfo")
	//前端获取后台微信用户对象,
	public String getUserInfo(String openid){
		TUser userinfo = userService.findUserByopenid(openid);
		return JSON.toJSONString(userinfo);
	}
	

}
